package com.bit.cfdi.web.dao.impl;

import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.bit.cfdi.web.dao.GiroDAO;
import com.bit.cfdi.web.domain.Giro;
import com.bit.cfdi.web.domain.Negocio;

@Repository
public class GiroDAOImpl extends HibernateDaoSupport implements GiroDAO{

	protected Logger log = LogManager.getLogger(this.getClass().getName());

	@Autowired
	public void init(final SessionFactory sessionFactory) {
		setSessionFactory(sessionFactory);
	}	

	@Override
	 @Transactional public void save(Giro giro)  throws DataAccessException {
		getHibernateTemplate().saveOrUpdate(giro);
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional public List<Giro> getAll() throws DataAccessException {
		List<Giro> giroList = null;
		
		giroList = getHibernateTemplate().find("from Giro");
		
		return giroList;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional public Giro getGiroByNegocio(Negocio negocio) throws DataAccessException {
		List<Giro> giro = null;		
		giro = getHibernateTemplate().find("SELECT ng.giro FROM NegocioGiro as ng " +
				"WHERE ng.negocio.idNegocio=?", negocio.getIdNegocio());
		return giro.size()>0? giro.get(0):null;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional public List<Giro> getGiroDefault() throws DataAccessException {
		return getHibernateTemplate().find("FROM Giro WHERE isDefault=true");
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public Giro getGiroByDescripcion(String descripcion) throws DataAccessException {
		List<Giro> giro = null;
		giro = getHibernateTemplate().find(
				"FROM Giro as giro WHERE giro.descripcion=?", descripcion);
		return giro.size()>0? giro.get(0):null;
	}

}
